package co.edu.aes.patrones.cliente.ventanas;

import co.edu.aes.patrones.forwardreceiver.mensajes.MensajeUDP;
import co.edu.aes.patrones.forwardreceiver.transmisor.Transmisor;
import co.edu.aes.patrones.forwardreceiver.utilidades.ComunicacionException;
import co.edu.aes.patrones.forwardreceiver.utilidades.TipoComunicacion;
import co.edu.aes.patrones.forwardreceiver.utilidades.TiposEncabezados;
import co.edu.aes.patrones.forwardreceiver.utilidades.Utilidades;
import java.awt.Color;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author windows
 */
public class RegistrarCliente extends javax.swing.JFrame {

    private static final long serialVersionUID = 1L;
    //Configuración Cliente
    private static String direccionIP;
    private static int puertoTCP = 1024;
    //Configuración UDP para registro y eliminación con despachador.
    private static String direccionIPMulticast;
    private static int puertoUDP;

    /**
     * Creates new form RegistrarCliente
     */
    public RegistrarCliente() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT
     * modify this code. The content of this method is always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        ip_label = new javax.swing.JLabel();
        nombre_label = new javax.swing.JLabel();
        boton_registrar = new javax.swing.JButton();
        boton_cancelar = new javax.swing.JButton();
        ip_texto = new javax.swing.JTextField();
        nombre_texto = new javax.swing.JTextField();
        puerto_texto = new javax.swing.JTextField();
        puerto_label = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Registro");

        ip_label.setText("IP dispatcher");

        nombre_label.setText("Nombre");

        boton_registrar.setText("Registrar");
        boton_registrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boton_registrarActionPerformed(evt);
            }
        });

        boton_cancelar.setText("Cancelar");
        boton_cancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boton_cancelarActionPerformed(evt);
            }
        });

        nombre_texto.setToolTipText("");

        puerto_texto.setToolTipText("");

        puerto_label.setText("Puerto dispatcher");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(35, 35, 35)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(puerto_label)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(ip_label)
                        .addComponent(nombre_label, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(puerto_texto, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(ip_texto, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(nombre_texto, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(33, 33, 33))
            .addGroup(layout.createSequentialGroup()
                .addGap(56, 56, 56)
                .addComponent(boton_registrar)
                .addGap(55, 55, 55)
                .addComponent(boton_cancelar)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(33, 33, 33)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ip_label)
                    .addComponent(ip_texto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(puerto_label)
                    .addComponent(puerto_texto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nombre_label)
                    .addComponent(nombre_texto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(35, 35, 35)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(boton_registrar)
                    .addComponent(boton_cancelar))
                .addContainerGap(21, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-368)/2, (screenSize.height-237)/2, 368, 237);
    }// </editor-fold>//GEN-END:initComponents

    private void boton_cancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boton_cancelarActionPerformed
        dispose();
    }//GEN-LAST:event_boton_cancelarActionPerformed

    private void boton_registrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boton_registrarActionPerformed
        if (ip_texto.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Ingrese la IP del dispatcher", "ERROR", JOptionPane.ERROR_MESSAGE);
        } else if (puerto_texto.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Ingrese el puerto del dispatcher", "ERROR", JOptionPane.ERROR_MESSAGE);
        } else if (nombre_texto.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Ingrese el nombre del cliente", "ERROR", JOptionPane.ERROR_MESSAGE);
        } else {
            MensajeUDP mensajeUDP = new MensajeUDP();
            Transmisor transmisor = new Transmisor();
            puertoUDP = 1116;
            direccionIPMulticast = "224.2.2.2";
            try {
                direccionIP = Utilidades.resolverDireccionLocal();
                //Mensaje de inicio del cliente, registro en el despachador.
                mensajeUDP.setEncabezado(TiposEncabezados.REGISTRO.name());
                mensajeUDP.setNombreDireccion(nombre_texto.getText());
                mensajeUDP.getUbicacionFisica().setDireccionIP(direccionIP);
                mensajeUDP.getUbicacionFisica().setPuerto(puertoTCP);

                transmisor.enviar(direccionIPMulticast, puertoUDP, TipoComunicacion.UDP, mensajeUDP);
            } catch (ComunicacionException ex) {
                Logger.getLogger(Cliente.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
                JOptionPane.showMessageDialog(this, "Comunicación fallida con el dispatcher, por favor verifique la dirección",
                        "ERROR", JOptionPane.ERROR_MESSAGE);
            }
            java.awt.EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    new Cliente(nombre_texto.getText(), direccionIP, ip_texto.getText(),puerto_texto.getText()).setVisible(true);
                }
            });
            dispose();
        }
    }//GEN-LAST:event_boton_registrarActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton boton_cancelar;
    private javax.swing.JButton boton_registrar;
    private javax.swing.JLabel ip_label;
    private javax.swing.JTextField ip_texto;
    private javax.swing.JLabel nombre_label;
    private javax.swing.JTextField nombre_texto;
    private javax.swing.JLabel puerto_label;
    private javax.swing.JTextField puerto_texto;
    // End of variables declaration//GEN-END:variables
}
